import {request} from '@/common/request/index.js'
import __localstorage from '@/common/localstorage/localstorage.js';

export default ({
	//code码 渠道 H5 或者 MP ，成功回调函数，失败回调函数
	getOpenid(code, channel_from, callback,errorback) {
		
		if (!code || !channel_from) return uni.showToast({
			title: '缺少主要参数，请刷新重试'
		});
		let goOpenid = () => {
			request.get('/weixin/authorize/getopenid.ashx', {
					data: {
						channel_from: channel_from,
						code: code || ''
					}
				})
				.then(res => {
					let result = res.data;
					if (result && result.Status == "ok") {
						__localstorage.storeOpen.setMyopenid(result.Tag);
						if (callback) callback(result.Tag);
					}else if(errorback) errorback()
					
				})
				.catch(error => {
					uni.showModal({
						title: '支付初始化失败，请稍候重试'
					})
				});
		};
		goOpenid();
	},
	setWeixinpay(options) {
		let orderid = options.orderid,
			openid = options.openid,
			channel_from = options.channel_from,
			callback = options.callback;
		if (!orderid || !openid || !channel_from) return uni.showToast({
			title: '缺少主要参数，请刷新重试'
		});
		
		uni.showLoading({
			mask:true
		})
		request.get('/weixin/mp_pay.ashx', {
				data: {
					openid: openid,
					orderid: orderid,
					channel_from: channel_from
				}
			})
			.then(res => {
				uni.hideLoading()
				let result = res.data;
				if (result && result.Status == "ok") {
					let tag = JSON.parse(result.Tag)
					if (callback) callback(tag)
				}
			})
			.catch(error => {
				uni.hideLoading()
				uni.showModal({
					title: '支付失败，请稍候重试'
				})
			});
			
	},
	checkLogin_MP(callback) {
		uni.showLoading({
			title: '正在加载模块...',
			mask:true
		})
		uni.login({
			provider: 'weixin',
			timeout: 5000,
			success(loginRes) {
				if (loginRes.errMsg == 'login:ok') {
					if (callback) callback(loginRes.code);
				}
			},
			fail() {
				uni.showModal({
					title: '网络错误，请稍候重试'
				})
			},
			complete(res) {
				uni.hideLoading()
			}
		});
	},
	
	getUrlKey: function(name) {
		return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[
			1].replace(/\+/g, '%20')) || null
	},
})
